import constRouteMap, { NotFound } from '@/router/const_router'
import asyncRouteMap from '@/router/async_router'

const state = {
  constRoutes: constRouteMap,
  asyncRoutes: []
}

const mutations = {
  SET_ASYNC_ROUTES: (state, routes) => {
    routes.push(NotFound)
    state.asyncRoutes = routes
  }
}

const actions = {
  generateRoutes({ commit }, permissions) {
    return new Promise(resolve => {
      const routes = formatRoutes(asyncRouteMap, permissions)
      commit('SET_ASYNC_ROUTES', routes)
      resolve(routes)
    })
  }
}

export function formatRoutes(asyncRouter, permissions) {
  const routes = asyncRouter.map(({ path, component, name, meta, redirect, children }) => {
    const route = { path, name, meta, redirect, children }
    if (component === 'Layout') {
      route.name = name
      route.component = resolve => require(['@/layout/index.vue'], resolve)
    } else if (typeof (component) === 'string') {
      if (permissions.includes(component)) {
        route.component = resolve => require([`@/views/${component}.vue`], resolve)
      } else {
        route.component = resolve => require([`@/views/no_permission/index.vue`], resolve)
      }
    } else {
      route.component = component
    }
    if (children && children instanceof Array) {
      route.children = formatRoutes(children, permissions)
    }
    return route
  })
  return routes
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
